# 当Query为空，打包data要对空对象额外处理，但是getattr即调用缺失属性时返回None，并且nullobject判断为False
class NullObject:
    """万能空对象，任何属性访问返回 None，但在条件判断时为 False"""
    def __getattr__(self, name):
        return None

    def __bool__(self):
        return False

    def __repr__(self):
        return "<NullObject>"

    def __len__(self):
        return 0

NULL_OBJECT = NullObject()

def QueryOneInstance(class_, filter_):
    instance = class_.query.filter_by(**filter_).first()
    return instance if instance is not None else NULL_OBJECT

# 问题在于多次query，假如后一个query关联前一个，那么filter引用前一个对象，如果前一个对象未nullobject，那么对于第二次查找为None，实际上第二次查找应该为nullobject
def QueryOneRelatedInstance(class_, filter_,relate_object):
    if relate_object is None or relate_object is NULL_OBJECT:
        return NULL_OBJECT
    return QueryOneInstance(class_, filter_)

def QueryMultipleInstances(class_, filter_):
    return class_.query.filter_by(**filter_).all()

def QueryMultipleRelatedInstances(class_, filter_, relate_object):
    if relate_object is None or relate_object is NULL_OBJECT:
        return []
    return QueryMultipleInstances(class_, filter_)

def QueryOrCreateOneInstance(class_, filter_):
    ins =  class_.query.filter_by(**filter_).first()
    if ins is None:
        ins = class_(**filter_)
    return ins

